import { queryArticleList } from "@/api/article.api";
import { ArticleList } from "@/types/article";
import { Pagination } from "@/types/pagination";
import { useEffect, useState } from "react";

export const useArticleList = (): {
  articleList: ArticleList;
  pagination: Pagination;
  tagChange: (id: string) => void;
  categoryChange: (id: string) => void;
  goToPage: () => void;
} => {
  const [tagId, setTagId] = useState<string>("");
  const [category, setCategory] = useState<string>("");
  const [articleList, setArticleList] = useState<ArticleList>([]);
  const [pagination, setPagination] = useState<Pagination>({
    pageNo: 1,
    pageSize: 30,
    total: 0,
  });
  const getArticleList = async () => {
    const { pageNo, pageSize } = pagination;

    const params = {
      pageNo,
      pageSize,
      categoryId: category,
      tagIds: tagId ? [tagId] : [],
    };

    const res = await queryArticleList(params);
    if (res.code === 200 && res.data) {
      const list = res.data.rows || [];
      setArticleList(pageNo === 1 ? list : articleList.concat(list));
      setPagination({
        ...pagination,
        total: res.data.total || 0,
      });
    }
  };
  const tagChange = (id: string): void => {
    setTagId(() => id);
    setPagination({
      ...pagination,
      pageNo: 1,
    });
  };
  const categoryChange = (id: string): void => {
    setCategory(id);
    setPagination({
      ...pagination,
      pageNo:1
    });
  };
  const goToPage = (): void => {
    setPagination((prev) => ({
      ...prev,
      pageNo: ++prev.pageNo,
    }));
    getArticleList();
  };
  useEffect(() => {
    getArticleList();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.pageNo, tagId, category]);

  return {
    articleList,
    pagination,
    tagChange,
    categoryChange,
    goToPage,
  };
};
